from datetime import datetime
from typing import TYPE_CHECKING, Dict, Any

from config.logging_config import get_logger
from prompt.sys_prompt import SystemPrompts

if TYPE_CHECKING:
    from AIAgents.model.NavigationAgent import NavigationAgentState

# 设置日志记录器
logger = get_logger(__name__)


def think_node(agent, state: 'NavigationAgentState') -> 'NavigationAgentState':
    """思考节点 - 使用智能LLM分析当前状态并决定下一步行动"""
    logger.info("🤔 思考节点开始")

    try:
        iteration = state.get("iteration_count", 0)
        state["iteration_count"] = iteration + 1

        # 检查是否超过最大迭代次数
        if iteration >= state.get("max_iterations", 5):
            logger.info("📊 达到最大迭代次数，准备结束")
            state["next_action"] = "finish"
            state["should_continue"] = False
            return state

        # 构建思考提示词
        thought_prompt = agent._build_thought_prompt(state)

        # 构建上下文，只使用最后一个工具/MCP结果
        tool_results = state.get("tool_results", [])
        mcp_results = state.get("mcp_results", [])
        
        context = {
            "input": state.get("input", ""),
            "rag_results": state.get("rag_results", []),
            "tool_results": [tool_results[-1]] if tool_results else [],
            "mcp_results": [mcp_results[-1]] if mcp_results else [],
            "history_memory_context": state.get("history_memory_context", {})
        }

        # 使用BaseAgent的智能LLM调用方法
        intelligent_result = agent._invoke_llm_with_tools(thought_prompt,
                                                          custom_system_prompt=SystemPrompts.build_format_sys_prompt(),
                                                          context=context)

        # 存储智能响应到状态中
        state["intelligent_response"] = intelligent_result
        state["current_thought"] = intelligent_result.get("reasoning", "")

        # 记录推理步骤
        reasoning_step = {
            "iteration": iteration + 1,
            "thought": intelligent_result.get("reasoning", ""),
            "action": intelligent_result.get("action", "direct_answer"),
            "timestamp": datetime.now().isoformat()
        }

        state["reasoning_steps"] = state.get("reasoning_steps", [])
        state["reasoning_steps"].append(reasoning_step)
    except Exception as e:
        logger.error(f"❌ 思考节点失败: {str(e)}")
        state["error"] = f"思考失败: {str(e)}"
        state["intelligent_response"] = {"action": "direct_answer", "content": f"思考失败: {str(e)}"}
        state["should_continue"] = False

    return state


def should_continue_execution(state: Dict[str, Any]) -> str:
    """判断是否继续执行 - 通用逻辑"""
    try:
        # 优先检查智能响应中的should_continue字段
        intelligent_response = state.get("intelligent_response", {})
        llm_should_continue = intelligent_response.get("should_continue", True)

        # 检查状态中的should_continue字段
        state_should_continue = state.get("should_continue", True)

        # 检查迭代次数
        iteration = state.get("iteration_count", 0)
        max_iterations = state.get("max_iterations", 5)

        # 检查是否有错误
        has_error = bool(state.get("error", ""))

        # 综合判断是否应该继续
        if has_error:
            logger.info("🏁 存在错误，结束执行循环")
            return "finish"
        elif not llm_should_continue:
            logger.info("🏁 智能响应指示不继续，结束执行循环")
            return "finish"
        elif not state_should_continue:
            logger.info("🏁 状态指示不继续，结束执行循环")
            return "finish"
        elif iteration >= max_iterations:
            logger.info(f"🏁 达到最大迭代次数({max_iterations})，结束执行循环")
            return "finish"
        else:
            logger.info(
                f"🔄 继续执行循环 (迭代: {iteration}/{max_iterations}, LLM继续: {llm_should_continue}, 状态继续: {state_should_continue})")
            return "continue"

    except Exception as e:
        logger.error(f"❌ 判断继续执行失败: {str(e)}")
        return "finish"
